package postgres

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	logger "simcard/collector/logger"
	"simcard/config"
	"simcard/errors"
	"simcard/model"
	"simcard/model/entity"
	"simcard/utils"
	"strings"
)

var Prepaid = &prepaid{}

type prepaid struct{}

func init() {
	Register(Prepaid)
}

func (a *prepaid) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.Prepaid{}
		if db.Migrator().HasTable(p) {
			logger.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := db.AutoMigrate(p); err != nil {
			logger.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			logger.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *prepaid) Create(ctx context.Context, m *entity.Prepaid) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *prepaid) Find(ctx context.Context, in *model.PrepaidInfoRequest) (*entity.Prepaid, error) {
	e := &entity.Prepaid{}

	q := GetDB(ctx).Model(&entity.Prepaid{})

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}
	err := q.First(&e, in.Id).Error
	return e, err
}

// Update
func (a *prepaid) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.Prepaid{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *prepaid) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.Prepaid{}, id).Error
}

// List query list
func (a *prepaid) List(ctx context.Context, in *model.PrepaidListRequest, opts ...model.QueryOptions) (int, []*entity.Prepaid, error) {

	var (
		opt      = model.GetQueryOption(opts...)
		q        = GetDB(ctx).Model(&entity.Prepaid{})
		err      error
		total    int64
		prepaids []*entity.Prepaid
	)

	if in.Id != nil {

		q = q.Where("id = ?", in.Id)

	}

	if len(in.Ids) > 0 {

		q = q.Where("id IN ?", in.Ids)

	}

	if in.PaymentId != nil {

		q = q.Where("payment_id = ?", in.PaymentId)

	}

	if in.EbikeId != nil {

		q = q.Where("ebike_id = ?", in.EbikeId)

	}

	if len(in.EbikeIds) > 0 {

		q = q.Where("ebike_id IN ?", in.EbikeIds)

	}

	if in.Sn != nil {

		q = q.Where("sn like ?", utils.SqlLike(in.Sn))

	}

	if in.EffectiveDate != nil {

		q = q.Where("effective_date = ?", in.EffectiveDate)

	}

	if in.ExpiredDate != nil {

		q = q.Where("expired_date = ?", in.ExpiredDate)

	}

	if in.Status != nil {

		q = q.Where("status = ?", in.Status)

	}

	if len(in.Statuses) > 0 {

		q = q.Where("status IN ?", in.Statuses)

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if len(opt.Conditions) > 0 {
		q = q.Where(strings.Join(opt.Conditions, " AND "))
	}

	if len(opt.SelectFields) > 0 {
		q = q.Select(opt.SelectFields)
	}

	if len(opt.OrderFields) > 0 {
		q = q.Order(fmt.Sprintf("%v", model.ParseOrder(opt.OrderFields)))
	}

	b := !opt.OnlyCount && !opt.OnlyList
	if opt.OnlyCount || b {
		if err = q.Count(&total).Error; err != nil {
			return 0, nil, err
		}
	}

	if opt.OnlyList || b {
		if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&prepaids).Error; err != nil {
			return 0, nil, err
		}
	}
	return int(total), prepaids, nil
}

// ExecTransaction execute database transaction
func (a *prepaid) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
